package com.student.controller;


import com.student.service.ManageService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.student.entity.Menu;
import java.util.Map;

/**
 * Created by dongge on 16/9/16.
 */
@Controller
public class MenuController {

    private final static String RLIST = "redirect:/menus";
    private final static String LIST = "menu/list";
    private final static String INPUT = "menu/input";

    @Autowired
    private ManageService manageService;

    @RequiresRoles("admin")
    @RequestMapping("/menus")
    public String list(Map<String,Object> map){
        map.put("menus",manageService.getAll(Menu.class));
        return LIST;
    }

    @RequestMapping(value = "/menu",method = RequestMethod.GET)
    public String input(Map<String,Object> map){
        map.put("menu",new Menu());
        map.put("menus",manageService.getAll(Menu.class));
        return INPUT;
    }

    @RequestMapping(value = "/menu",method = RequestMethod.POST)
    public String create(Menu menu){
        if(menu.getParent().getId()!=null){
            Menu parent = (Menu)manageService.get(Menu.class, menu.getParent().getId());
            menu.setParent(parent);
        } else {
            menu.setParent(null);
        }
        manageService.save(Menu.class, menu);
        return RLIST;
    }

    @RequestMapping(value = "/menu/{id}",method = RequestMethod.GET)
    public String edit(@PathVariable("id")Integer id, Map<String,Object> map){
        map.put("menu",manageService.get(Menu.class, id));
        map.put("menus", manageService.getAll(Menu.class));
        return INPUT;
    }

    /**
     * 有问题还要改才行??????
     * @param id
     * @param parentId
     * @param map
     */
    @ModelAttribute
    public void getMenu(@RequestParam(value = "id",required = false)Integer id,
                        @RequestParam(value = "parent.id",required = false)Integer parentId,
                        Map<String,Object> map){
        if(id !=null){
            Menu menu = (Menu)manageService.get(Menu.class, id);
            map.put("menu",menu);
        }
    }

    @RequestMapping(value = "/menu",method = RequestMethod.PUT)
    public String update(Menu menu){
        if(menu.getParent().getId() == null){
            menu.setParent(null);
        }else {
            Integer id = menu.getParent().getId();
            menu.setParent((Menu)manageService.get(Menu.class, id));
        }
        manageService.update(Menu.class, menu);
        return RLIST;
    }

    @RequestMapping(value = "/menu/{id}",method = RequestMethod.DELETE)
    public String delete(@PathVariable("id")Integer id){
        manageService.delete(Menu.class, id);
        return RLIST;
    }
}
